/*
 * @Descripttion: 
 * @version: 
 * @Author: Zuo
 * @Date: 2021-09-29 10:23:44
 * @LastEditors: Zuo
 * @LastEditTime: 2021-09-30 14:51:17
 */

import { reactive, UnwrapRef ,toRaw} from "vue"

import { User } from "../../../types"
import { Form } from "ant-design-vue"
import { successMessage } from "../../../common/info"
import { TIP } from "../../../common/tip"
import { login } from "../../../api/module/user"
import { routerPush, routerReplace } from "../../../router/scripts/router-trigger"

const userInfo: UnwrapRef<User> = reactive({
    name: null,
    pwd: null,
    code:null,
    codeId:null
})

const userInfoRules = reactive({
    name: [{
        required: true,
        message: "Please input your username!"
    }, {
        max: 11,
        min: 4,
        message: "A minimum of 4 and a maximum of 11!"
    }
    ],
    pwd: [{
        required: true,
        message: "Please input your password!"
    }, {
        max: 16,
        min: 5,
        message: "A minimum of 5 and a maximum of 16!"
    }
    ],
    code: [{
        required: true,
        message: "Please input your code!"
    }, {
        max: 4,
        min: 4,
        message: "length is 4!"
    }
    ]
})
/* 登陆校验规则 */
const {resetFields , validate, validateInfos } = Form.useForm(userInfo, userInfoRules)
/* 登陆逻辑 */
//注意： 由于sotre 使用时机必须在setup、所以由页面传入过来。 
async function userLogin(store:any) {
    try {
        await validate()
        const data:any = await login(userInfo)
        if(!data.err){
            console.log(store)
            data.data.userName = userInfo.name;
            const userData = Object.assign({},toRaw(userInfo),data.data)
            store.dispatch('login',userData)
            successMessage(TIP.LOGIN_SUCCESS)
            resetFields()
            return routerPush("/home")
        }
    } catch {
       // resetFields()
    }
}

async function userLogOut(store:any) {
        store.dispatch('logout')
        return routerReplace("/login")
}


export {
    userLogin,
    userLogOut,
    userInfo,
    validateInfos
}